# -*- coding: UTF-8 -*_
from PIL import Image
from pytesseract import *
import requests
from io import BytesIO
import time, threading
import os
def yzm(s):        #s是图片本地路径

    im = Image.open(s)
    im.show()
    #return input('输入验证码\n')
    #如果你有安装ocr图像识别啥啥的就把下面代码放出来上面那行删了~（不用手动输入）否则与pytesseract有关的东西全删了手动输入验证码也行

    print('正在识别验证码')
    imgry = im.convert('L')#把图片变成灰色
    threshold = 140

    table = []
    for i in range(256):#二值化变成黑白

        if i < threshold:
            table.append(0)
        else:
            table.append(1)
    out = imgry.point(table, '1')
    asd = pytesseract.image_to_string(out,lang='fyx')#然后就是验证码识别咯，lang包来自小贩子的喂图调教成果（机器学习）~~~
    print('验证码为 '+asd)
    return  asd


zh=1706010216
mm=233233
baseurl='http://202.119.113.148'
img_src=baseurl+'/validateCodeAction.do?random=0.5'#获取验证码的链接
url=baseurl+'/gradeLnAllAction.do?type=ln&oper=qbinfo&lnxndm'
url1=baseurl+'/loginAction.do'#登录链接
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36'}#请求头
data=[
    ('kcId', '0601059_01'),
    ('kcId', '0601081_01'),
    ('kcId', '0601004_01'),
    ("preActionType", '2'),
    ("actionType",'9'),
      ]

'''
fw函数是用来验证密码是否正确的函数
mm参数是密码
xc参数是线程编号~~
'''
def dl(zh,mm):#登录
    valcode = requests.get(img_src) #从验证码链接获取图片
    cookies = valcode.cookies.get_dict() #保存cookies
    image = Image.open(BytesIO(valcode.content)) #图片获取
    #path1 = os.path.abspath('.')
    lj='yzm.bmp'#图片保存路径
    try:
        image.save(lj)#保存图片
    except:
        return dl(zh,mm)
    yzm_str = yzm(lj)
    if (len(yzm_str) != 4):#验证码不是4位说明识别出错
        return dl(zh,mm)
    mms=str(mm)
    datadl = {        #需要post的数据
        "zjh": str(zh),
        "mm": mms,
        "v_yzm": yzm_str,
    }
    print('正在登录')
    response = requests.post(url1, data=datadl, headers=headers, cookies=cookies)#获取网页
    htxt = response.text#网页源代码
    if ('您的密码不正确，请您重新输入' in htxt):
        print('密码错误')
        return '0'
    elif ('你输入的验证码错误' in htxt):
        return dl(zh, mm)
    else:
        print(htxt)
        print('登录成功')
        return cookies

s=dl(zh,mm)
pd = False
xz=False
def run_thread(n):
    i=n
    global pd
    global xz
    while True:
        response = requests.post(baseurl+'/xkAction.do', data=data, headers=headers,
                                 cookies=s)  # 获取网页
        if (pd):
            return
        print(response.text)

        if '成功' in response.text:
            pd = True
            print('线程 ' + str(i) + ' 选课成功')
            # print(response.text)
            return

        if '不能选修' in response.text or 'Cannot find bean zhjw' in response.text:
            if (pd):
                continue
            print('选课失败,该课程不能选修~')
            pd = True
            return
        print('线程 ' + str(i) + ' 选课失败')

def mkdir(path):
    folder = os.path.exists(path)
    if not folder:  # 判断是否存在文件夹如果不存在则创建为文件夹
        os.makedirs(path)  # makedirs 创建文件时如果路径不存在会创建这个路径

if(s=='0'):
    print('导出失败')
else:
    xczs = 16  # 这是线程数量，我放了128个差点把电脑卡死~~~
    mkdir('yzm')
    i=1
    t = {}
    while i <= xczs:
        t[i] = threading.Thread(target=run_thread, args=[i])
        print('创建线程 '+str(i))
        i += 1
    i = 1
    while i <= xczs:
        t[i].start()
        i += 1